@echo off

set _j_function=%1

call :pack_args _j_args 1 %*
call :!_j_function! !_j_args!

call :unset _j_function _j_args
exit /B

:: param: start_path detect_path result_path variable
:detect_path
	set _j_arg=%~1
	set _j_disk="%~d1\"


	:_loop_detect_path
		if exist "!_j_arg!%2" (
			set %4=!_j_arg!%3
			call :unset _j_arg _j_disk 
			exit /B
		)

		for %%a in ( "!_j_arg!." ) do set _j_arg=%%~dpa
		if "!_j_arg!" == "!_j_disk!" (
			call :unset _j_arg _j_disk 
			exit /B
		)

	goto :_loop_detect_path

:detect_tools_path
	call :detect_path %1 tools\cmake tools J_TOOLS_PATH
	exit /B

:detect_external_path
	call :detect_path %1 external external J_EXTERNAL_PATH
	exit /B


:detect_cmake_path 
	call :detect_tools_path %1
	if defined J_CMAKE_VERSION (
		set J_CMAKE_PATH=!J_TOOLS_PATH!\cmake\!J_CMAKE_VERSION!\bin\cmake.exe
		if exist "!J_CMAKE_PATH!" exit /B 0
		exit /B 1
	)

	set J_CMAKE_PATH=
	for /f "usebackq delims=*"  %%a in (`where /F cmake.exe`) do set J_CMAKE_PATH=%%~a

	exit /B

:do_nothing
	exit /B


:print
	set _j_echo="!J_CMAKE_PATH!" -E cmake_echo_color --no-newline

	if /I "%1"=="ERROR" (
		set _j_msg_type="[ERROR] "
		set _j_echo=!_j_echo! --red --bold
	) else if /I "%1"=="INFO" (
		set _j_msg_type="[INFO] "
		set _j_echo=!_j_echo! --green
	) else if /I "%1"=="DEBUG" (
		set _j_msg_type="[DEBUG] "
		set _j_echo=!_j_echo! --white
	) else (
		set _j_msg_type=++ 
		set _j_echo=!_j_echo! --normal
	)


	call :pack_args _j_print_args 1 %*
	set _j_msg_text=""
	if not defined J_CMAKE_PATH (
		for %%a in (!_j_msg_type!) do echo %%~a !_j_print_args!
	)else (
		for %%a in (!_j_msg_type!) do (
			set _j_msg_text=%%~a
			for %%b in (!_j_print_args!) do (
				set _j_msg_text=!_j_msg_text! " " %%b
			)
			!_j_echo! !_j_msg_text! 
		)
		echo.
	)

	call :unset _j_msg_type _j_print_args _j_echo _j_msg_text
	exit /B

:set_echo
	set j_log_info=call !J_BUILD_SRC!tools\function.bat print INFO 
	set j_log_error=call !J_BUILD_SRC!tools\function.bat print ERROR 
	set j_log_mesg=call !J_BUILD_SRC!tools\function.bat print  MESG 
	set j_log_debug=call !J_BUILD_SRC!tools\function.bat print DEBUG 

	exit /B

:pack_args
	set _j_ret=%1
	set /A _j_skip=%2 + 2

	:_loop_pack_args_skip
	if !_j_skip! GTR 0 (
		shift
		set /A _j_skip=!_j_skip! - 1
		goto _loop_pack_args_skip
	)

	set _j_tmp=%1
	:_loop_pack_args
	shift
	if "%~1" NEQ "" ( 
		set _j_tmp=!_j_tmp! %1
		goto _loop_pack_args
	)

	set !_j_ret!=!_j_tmp!

	call :unset _j_tmp _j_ret
	exit /B

:unset
	:_loop_unset
	if "%1" NEQ "" ( 
		set %1=
		shift
		goto _loop_unset
	)
	
	exit /B



